<template>
  <div class="user-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
      </template>
      
      <!-- 商户表格 -->
      <el-table 
        :data="list" 
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
        empty-text="暂无数据"
      >
        <el-table-column prop="Id" label="id" show-overflow-tooltip />
        <el-table-column prop="Name" label="上游平台名称" show-overflow-tooltip />
        <el-table-column prop="Code" label="上游平台代码"/>
        <el-table-column prop="BaseUrl" label="请求基础地址" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">更新</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/更新对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="平台名称" prop="Name">
          <el-input v-model="form.Name" placeholder="请输入平台名称" />
        </el-form-item>
        <el-form-item label="平台代码" prop="Code" v-if="dialogType === 'add'">
          <el-input v-model="form.Code" placeholder="请输入平台代码" />
        </el-form-item>
        <el-form-item label="请求基础地址" prop="BaseUrl">
          <el-input v-model="form.BaseUrl" placeholder="请输入请求基础地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { upstreamPlatFormList, createUpstreamPlatform, updateUpstreamPlatform } from '@/api/merchant'

// 响应式数据
const loading = ref(false)
const list = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' or 'edit'
const formRef = ref()
const editingId = ref(null) // 当前编辑的记录ID

// 表单数据
const form = reactive({
  Name: '',
  Code: '',
  BaseUrl: ''
})

// 表单验证规则
const formRules = {
  Name: [
    { required: true, message: '请输入平台名称', trigger: 'blur' }
  ],
  Code: [
    { required: true, message: '请输入平台代码', trigger: 'blur' }
  ],
  BaseUrl: [
    { required: true, message: '请输入请求基础地址', trigger: 'blur' }
  ]
}

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await upstreamPlatFormList({
      Page: currentPage.value,
      PageSize: pageSize.value,
    })
    if (res.code === 200) {
      list.value = res.data?.List || []
      total.value = res.data?.Total
    } else {
      ElMessage.error('获取商户列表失败')
    }
  } catch (error) {
    // ElMessage.error('获取商户列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  getList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  getList()
}

// 计算对话框标题
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增上游平台' : '更新上游平台'
})

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  editingId.value = null
  dialogVisible.value = true
  resetForm()
}

// 更新
const handleEdit = (row) => {
  dialogType.value = 'edit'
  editingId.value = row.Id
  dialogVisible.value = true
  // 填充表单数据
  Object.assign(form, {
    Name: row.Name,
    Code: row.Code,
    BaseUrl: row.BaseUrl
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    let res
    if (dialogType.value === 'add') {
      res = await createUpstreamPlatform({
        Name: form.Name,
        Code: form.Code,
        BaseUrl: form.BaseUrl
      })
    } else {
      res = await updateUpstreamPlatform({
        Id: editingId.value,
        Name: form.Name,
        BaseUrl: form.BaseUrl
      })
    }
    if (res.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
      handleClose()
      getList()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error(error)
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    Name: '',
    Code: '',
    BaseUrl: ''
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 生命周期
onMounted(() => {
  getList()
})
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

:deep(.el-table__header-wrapper .cell) {
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}

/* 让表格滚动条始终显示 */
::v-deep(.el-table__body-wrapper .el-scrollbar__bar) {
  display: block!important;
}
:deep(.el-scrollbar__thumb) {
  background-color: #909399;
  opacity: 1;
}
</style>